//
//  PhoneCall.swift
//
//  Created by sylar on 16/11/10.
//  Copyright © 2016年 sylar. All rights reserved.
//

import Foundation
import Contacts
import Alamofire
import CRPEarPhone
import SwiftyJSON

public enum PhoneCall {
    
    static func sendContactName(number: String) {
        var name: String = ""
        let status = CNContactStore.authorizationStatus(for: .contacts)
        if status == .authorized{
            let store = CNContactStore()
            
            let keys = [CNContactFamilyNameKey,CNContactGivenNameKey,CNContactPhoneNumbersKey,CNContactOrganizationNameKey,CNContactThumbnailImageDataKey]
            
            let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
            var pairName: [String] = []
            
            CRPEarPhoneSDK.sharedInstance.queryContactSupportSymbol { value in
                try? store.enumerateContacts(with: request, usingBlock: { (contact, stop) in
                    let phones = contact.phoneNumbers
                    for phoneNumber in phones{
                        var contactNumber = phoneNumber.value.stringValue
                        var symbols = ["+", "*", "#", " ", "(", ")", "-", ",", ";"]
                        for symbol in symbols {
                            if !value.contains(where: { $0 == symbol }) {
                                contactNumber = contactNumber.replacingOccurrences(of: symbol, with: "")
                            }
                        }
                        if contactNumber == number{
                            let lastName = contact.familyName
                            let firstName = contact.givenName
                            let organization = contact.organizationName
                            
                            var fullName = lastName + firstName
                            var isContains = false
                            for char in fullName.utf8{
                                if (char > 64 && char < 91) || (char > 96 && char < 123){
                                    isContains = true
                                    break
                                }
                            }
                            if isContains && lastName != "" && firstName != ""{
                                fullName = firstName + " " + lastName
                            }
                            if fullName == ""{
                                fullName = organization
                            }
                            
                            if fullName == "" || fullName == nil{
                                return
                            }
                            if contactNumber == number{
                                if name == ""{
                                    name = fullName
                                    CRPEarPhoneSDK.sharedInstance.sendCurrentCallerName(phoneNumber: number, name: fullName)
                                }
                            }
                            pairName.append(fullName)
                        }
                    }
                    
                    if name == "" && pairName.count > 0{
                        if let fullName = pairName.first {
                            CRPEarPhoneSDK.sharedInstance.sendCurrentCallerName(phoneNumber: number, name: fullName)
                        }
                    }
                })
            }
            
        } else{
            if let num = Int(number), num > 999999{
                PhoneCall.sogou(number as! String)
            }
        }
    }
    
    static func sogou(_ number:String) {
        if getCurrentLanguage() == "cn"{
            let tel = number.replacingOccurrences(of: "-", with: "")
            let url = "https://www.sogou.com/reventondc/inner/vrapi"
            AF.request(url, method: .get, parameters: ["number": tel, "type": "json", "callback":"show"]).responseString(completionHandler: { (response) in
                
                switch response.result {
                case .success(let dataJsonStr):
                    var jsonString:String = dataJsonStr
                    jsonString = jsonString.replacingOccurrences(of: "show(", with: "")
                    jsonString = jsonString.replacingOccurrences(of: ")", with: "")
                    if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) {
                        guard let json = try? JSON(data: dataFromString) else { return }
                        if let amount = json["Amount"].string {
                            let numString = json["NumInfo"].stringValue
                            let infoArr = numString.components(separatedBy: "：")
                            if (infoArr.count > 2) {
                                let numinfo = infoArr[1]
                                CRPEarPhoneSDK.sharedInstance.sendCurrentCallerName(phoneNumber: number, name: numinfo)
                            }
                        }
                    }
                case .failure(let error):
                    log.debug("sogou ERROR\(error.localizedDescription)")
                }
            })
        }
    }
}
